package com.zhiqiang.gameserver.nettydemo.time;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class TimeServer {

    private int port;
    public TimeServer(int port) {
        this.port = port;
    }

    public void run() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //boss   用来接收进来的连接
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        //worker  用来处理已经 被接收的连接
        try{
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            //ServerBootstrap 是一个启动 NIO 服务的辅助启动类。
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    //这里指定使用 NioServerSocketChannel 类来举例说明一个新的 Channel 如何接收进来的连接。
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new TimeServerHandler()); }

                    })
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);
                    // 绑定端口，开始接收进来的连接
                    ChannelFuture f = serverBootstrap.bind(port).sync();
                    // 等待服务器 socket 关闭 。
                    f.channel().closeFuture().sync();


        }finally {
            /**
             * 顾名思义，优雅的关闭
             */
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        int port;
        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        } else {
            port = 8888;
        }
        new TimeServer(port).run();
    }
}
